package org.oschina.plugin.topic;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.oschina.Constants;
import org.oschina.api.upload.UploadConfigType;
import org.oschina.api.upload.service.UploadConfigService;
import org.oschina.api.upload.service.UploadService;
import org.oschina.api.upload.vo.UploadConfigVo;
import org.oschina.bean.Result;
import org.oschina.helper.topic.AbstractTopicListener;
import org.oschina.plugin.PluginHelper;
import org.oschina.plugin.bean.PluginCreateSyncBean;
import org.oschina.util.ReflectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import aj.org.objectweb.asm.ClassReader;

/**
 * 添加插件同步处理
 */
@Component
public class PluginCreateSyncTopic extends AbstractTopicListener {

	private final static Logger logger=LoggerFactory.getLogger(PluginCreateSyncTopic.class);
	
	@Autowired
	private PluginHelper pluginHelper;
	@Autowired
	private UploadService uploadService;
	@Autowired
	private UploadConfigService uploadConfigService;

	@Override
	public String getKey()
	{
		return Constants.TOPIC_PLUGIN_CREATE_SYNC;
	}

	@Override
	public Class getType()
	{
		return PluginCreateSyncBean.class;
	}

	@Override
	public synchronized void handle(Object message)
	{
		PluginCreateSyncBean bean=(PluginCreateSyncBean) message;
		try
		{
			File file=new File(bean.getName());
			FileUtils.writeByteArrayToFile(file, bean.getClazzByte());
			ClassReader classReader=new ClassReader(bean.getClazzByte());
			String className=classReader.getClassName();
			
			UploadConfigVo uploadConfig=uploadConfigService._findVoById(UploadConfigType.PLUGIN);
			Result upload=uploadService._baseUpload(ReflectUtil.getClassPath()+"/"+getClassPath(className),uploadConfig.getType(),uploadConfig.getSize(),false,true,file);
			
			if(!upload.isSuccess())
			{
				logger.info("同步插件 '{}' 失败",file.getName());
				return;
			}
			
			pluginHelper.add(Class.forName(getClassName(className)));
			logger.info("同步插件 '{}' 成功",file.getName());
		}
		catch (Exception e)
		{
			logger.error("添加插件同步失败 - ",e);
		}
	}
	
	private String getClassName(String className)
	{
		return className.replace("/", ".");
	}
	
	private String getClassPath(String className)
	{
		return className.substring(0, className.lastIndexOf("/")+1);
	}
}